package main

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"strconv"
)

type Project struct {
	Name          string
	Homepage      *url.URL
	Contributiors []Contributor
}

type Contributor struct {
	ID   int
	Mail string
}

// 添加一个查询Mail的函数
func mailof(uid int, p Project) string {
	for _, contributor := range p.Contributiors {
		if contributor.ID == uid {
			return contributor.Mail
		}
	}
	return ""
}

// 给Project结构体添加一个method
func (p Project) mailof(uid int) string {
	for _, contributor := range p.Contributiors {
		if contributor.ID == uid {
			return contributor.Mail
		}
	}

	return ""
}

// 改进method，添加error返回
func (p Project) mailofp(uid int) (string, error) {
	for _, contributor := range p.Contributiors {
		if contributor.ID == uid {
			return contributor.Mail, nil
		}
	}

	return "", errors.New("没有找到ID为" + strconv.Itoa(uid) + "的 contributor")

}

func main() {
	hp, _ := url.Parse("https://example.com")
	aproject := Project{
		Name:     "A simple project",
		Homepage: hp,
		Contributiors: []Contributor{
			{
				ID:   20,
				Mail: "ann@example.com",
			},
			{
				ID:   30,
				Mail: "joe@example.com",
			},
		},
	}

	fmt.Printf("Project: %s\nHomepage: %s\nContributors:\n", aproject.Name, aproject.Homepage)
	for _, contributor := range aproject.Contributiors {
		fmt.Printf("- %s with ID %d\n", contributor.Mail, contributor.ID)
	}

	uid := 20

	// 调用普通函数
	mail := mailof(uid, aproject)
	fmt.Printf("Mail address of contributor with ID %d is %s\n", uid, mail)

	// 调用结构体的方法
	mail = aproject.mailof(uid)
	fmt.Printf("Mail address of contributor with ID %d is %s\n", uid, mail)

	// 调用改用的method
	uid = 33
	mail, err := aproject.mailofp(uid)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Mail address of contributor with ID %d is %s\n", uid, mail)
}
